package com.bustle.ejb.service.dao;

import java.util.List;

import javax.ejb.Local;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Local
public interface Dao<KeyType, Type>
{
  public void create(Type anObject);
  public Type retrieve(KeyType aKey);
  public List<Type> retrieveAll();
  public void update(Type anObject);
  public void delete(KeyType aKey);

  public class DefaultDao<KeyType, Type> implements Dao<KeyType, Type>
  {
    public DefaultDao(Class<? extends Type> aClass)
    {
      type = aClass;
    }

    @Override
    public void create(Type anObject)
    {
      entityManager.persist(anObject);
    }

    @Override
    public Type retrieve(KeyType aKey)
    {
      return entityManager.find(type, aKey);
    }

    @Override
    public List<Type> retrieveAll()
    {
      String className = type.getName().substring(type.getName().lastIndexOf(".") + 1);
      List<Type>  list = entityManager.createQuery("from " + className).getResultList();
      return list;
    }

    @Override
    public void update(Type anObject)
    {
      entityManager.merge(anObject);
    }

    @Override
    public void delete(KeyType aKey)
    {
      entityManager.remove(retrieve(aKey));
    }

    @PersistenceContext
    protected EntityManager entityManager;
    protected Class<? extends Type> type;
  }
}
